package iteration

import (
	"fmt"
	"net/http"
	"serve/model"

	"github.com/gin-gonic/gin"
)

func RegisterRouter(r *gin.RouterGroup) {
	r.GET("/list", List)
	r.POST("/add", Add)
	r.GET("/all", All)
}

// List  获取列表
func List(c *gin.Context) {
	var db = model.DB
	var iteration []model.Iteration
	var pid = c.Query("pid")
	result := db.Order("created_at desc")
	if len(pid) > 0 {
		result = result.Where("pid=?", pid)
	}
	result.Find(&iteration)
	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{"code": 400, "msg": fmt.Sprint(result.Error)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": iteration, "code": 200})
}

func Add(c *gin.Context) {
	var db = model.DB
	var p model.Iteration
	// res := c.ShouldBindQuery(&p)
	if c.ShouldBind(&p) == nil {
		db.Create(&p)
		c.JSON(http.StatusOK, gin.H{"data": p, "code": 200})
	} else {
		c.JSON(http.StatusOK, gin.H{"code": 400, "msg": "参数错误"})
	}

}

func All(c *gin.Context) {
	var db = model.DB
	var p []model.Iteration
	db.Order("created_at asc").Find(&p)
	c.JSON(http.StatusOK, gin.H{"data": p, "code": 200})
}
